package main

import (
	"flag"
	"fmt"
	"runtime"
	"sync"
	"time"
)

// 定义日志函数
func logInfo(message string) {
	logTime := time.Now().Format("2006-01-02 15:04:05")
	fmt.Printf("[%s] info %s\n", logTime, message)
}

// 控制 CPU 占用的 Goroutine
func cpuConsumer(cpuUsage int, wg *sync.WaitGroup) {
	defer wg.Done()

	for {
		// 计算忙碌和休眠时间
		busyTime := time.Duration(cpuUsage) * 10 * time.Millisecond
		idleTime := time.Duration(100-cpuUsage) * 10 * time.Millisecond

		// 增加工作负载
		start := time.Now()
		for time.Since(start) < busyTime {
			// 增加一些计算量
			for i := 0; i < 10000; i++ {
				_ = i * i
			}
		}
		time.Sleep(idleTime)
	}
}

func main() {
	// 定义命令行参数
	var cpuUsage int

	flag.IntVar(&cpuUsage, "u", 10, "CPU usage percentage (0-100)")

	flag.Parse()

	logInfo(fmt.Sprintf("Target CPU usage: %d%%", cpuUsage))

	// 启动多个 CPU 占用的 Goroutine
	numCores := runtime.NumCPU()
	var wg sync.WaitGroup
	wg.Add(numCores)

	for i := 0; i < numCores; i++ {
		go cpuConsumer(cpuUsage, &wg)
	}

	// 等待所有 Goroutine 结束
	wg.Wait()
}
